﻿

CREATE PROCEDURE [dbo].[balcon_UpdateSoldCont]
	-- Add the parameters for the stored procedure here
	@codUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    update Conturi set sold = DebitInitial-CreditInitial+ DebitPrecedent-CreditPrecedent+(SELECT Coalesce(SUM(ValoareLei),0) FROM Rulaje b
	where Conturi.Cont=b.ContDebit and Conturi.CodUnitate=b.Codunitate)
	where Conturi.CodUnitate=@codUnitate AND Conturi.Terminal = 1
	
	update Conturi set sold = sold - (SELECT Coalesce(SUM(ValoareLei),0) FROM Rulaje b
	where Conturi.Cont=b.Contcredit and Conturi.CodUnitate=b.Codunitate)
	where Conturi.CodUnitate=@codUnitate AND Conturi.Terminal = 1

	update Conturi set sold = (SELECT Coalesce(sum(a.sold),0) FROM Conturi a
	where dbo.IsContInclus(Conturi.cont,a.cont,Conturi.Terminal)=1 and Conturi.CodUnitate=a.Codunitate and a.Terminal=1)
	where Conturi.CodUnitate=@codUnitate AND Conturi.Terminal = 0
	


END